package com.ndood.admin.core.code;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ndood.admin.core.properties.AdminProperties;
import com.ndood.admin.core.properties.AliyunSmsProperties;
import com.ndood.core.validate.code.sms.SmsCodeSender;

/**
 * 短信发送器
 * @author ndood
 */
/*@Component*/
public class AdminSmsCodeSender implements SmsCodeSender {
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private AdminProperties adminProperties;
	
	public static final String CONNECTION_TIMEOUT = "15000";
	
	public static final String READ_TIMEOUT = "15000";

	@Override
	public void send(String mobile, String code) {
		try {
			AliyunSmsProperties dayu = adminProperties.getDayu();
			
			// 设置超时时间-可自行调整
			System.setProperty("sun.net.client.defaultConnectTimeout", CONNECTION_TIMEOUT);
			System.setProperty("sun.net.client.defaultReadTimeout", READ_TIMEOUT);
			IClientProfile profile = DefaultProfile.getProfile(dayu.getEndPoint(), dayu.getAccessKeyId(), dayu.getSecretKeyId());
			DefaultProfile.addEndpoint(dayu.getEndPoint(), dayu.getEndPoint(), dayu.getProduct(), dayu.getDomain());
			
			IAcsClient acsClient = new DefaultAcsClient(profile);
			// 组装请求对象
			SendSmsRequest request = new SendSmsRequest();
			// 使用post提交
			request.setMethod(MethodType.POST);
			// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
			request.setPhoneNumbers(mobile);
			// 必填:短信签名-可在短信控制台中找到
			request.setSignName(dayu.getSignName());
			// 必填:短信模板-可在短信控制台中找到
			request.setTemplateCode(dayu.getTemplateCode());
			request.setTemplateParam(String.format(dayu.getTemplate(), code, mobile));
			
			// 请求失败这里会抛ClientException异常
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				// 请求成功
				logger.info(mobile + "发送短信成功!");
				return;
			}
			throw new Exception(sendSmsResponse.getMessage());
		
		}catch(Exception e) {
			logger.error(mobile + "发送短信异常" + e.getMessage());
		}
	}
	
}
